package com.qdsgjsfk.vision.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.qdsgjsfk.vision.adapter.BlueToothAdapter;
import com.qdsgjsfk.vision.base.BaseActivity;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.eventbus.BlueTooth;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


import com.qdsgjsfk.vision.R;

import jz.joyoung.robot.util.LogUtil;
import util.NetworkUtil;

/**
 * 蓝牙列表界面
 *
 * @time 2020/12/11 9:13
 */
public class MyBlueTooth extends Activity {

    public static String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    RecyclerView lvBTDevices;
    BlueToothAdapter adtDevices;
    List<BleDevice> lstDevices = new ArrayList<BleDevice>();
    public static BluetoothSocket btSocket;

    Button btnDis, btnAbout;
    ImageView btn_back, btn_cancel;
    TextView tv_ip;
    long studentId, classId;
    private static ProgressDialog progressDialog;
    private static ProgressDialog mProgressDialog;
    private BluetoothAdapter bluetoothAdapter;
    protected String TAG = getClass().getSimpleName();
    protected Activity mContext;

    @SuppressLint("SetTextI18n")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main );
        mContext = this;
        EventBus.getDefault().register( this );
        initState();
        // Button 设置
        btnDis = (Button) this.findViewById( R.id.btnDis );
        btnDis.setOnClickListener( new ClickEvent() );

        btnAbout = (Button) this.findViewById( R.id.btnAbout );
        btnAbout.setOnClickListener( new ClickEvent() );
        btn_back = this.findViewById( R.id.btn_back );
        tv_ip = findViewById( R.id.tv_ip );
        btn_back.setOnClickListener( v -> finish() );
        btn_cancel = findViewById( R.id.btn_cancel );
        btn_cancel.setOnClickListener( v -> {
            if (BaseApplication.lastActivity == 0)
                startActivity( new Intent( mContext, TypeActivity.class ) );
            else if (BaseApplication.lastActivity == 1)
                startActivity( new Intent( mContext, StudentDetailActivity.class ) );
            else if (BaseApplication.lastActivity == 2)
                startActivity( new Intent( mContext, StudentDetailOtherActivity.class ) );
        } );

        lvBTDevices = this.findViewById( R.id.lvDevices );
        lvBTDevices.setLayoutManager( new LinearLayoutManager( this ) );
        adtDevices = new BlueToothAdapter( this, lstDevices );
        lvBTDevices.setAdapter( adtDevices );
        adtDevices.setOnItemClickLitener( position -> {
            showProgressDialog( mContext);
            if (!BleManager.getInstance().isConnected(lstDevices.get( position ))) {
                BleManager.getInstance().cancelScan();
                BleManager.getInstance().connect( lstDevices.get( position ), new BleGattCallback() {
                    @Override
                    public void onStartConnect() {
                        if (BaseApplication.currentBleDevice != null) {
                            BleManager.getInstance().disconnect( BaseApplication.currentBleDevice );
                        }
                    }

                    @Override
                    public void onConnectFail(BleDevice bleDevice, BleException exception) {
                        System.out.println( exception.getCode() );
                        dismissDialog();
                        Toast.makeText( mContext, "连接失败", Toast.LENGTH_LONG ).show();
                    }

                    @Override
                    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                        LogUtil.e( "currentBleDevice名字" + bleDevice.getName() + "---" + bleDevice );
                        dismissDialog();
                        BaseApplication.currentBleDevice = bleDevice;
                        BaseApplication.strName = bleDevice.getName();
                        Toast.makeText( mContext, bleDevice.getName() + " 连接成功", Toast.LENGTH_LONG ).show();
//                        BleActivity.launcher(mContext, bleDevice);
                        startActivity( new Intent( mContext, TypeActivity.class ) );
                    }

                    @Override
                    public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                        Toast.makeText( mContext, bleDevice.getName() + " 断开连接", Toast.LENGTH_LONG ).show();
                        BaseApplication.currentBleDevice = null;
                    }
                } );

            }
        } );


        studentId = getIntent().getLongExtra( "studentId", 0 );
        classId = getIntent().getLongExtra( "classId", 0 );

        if (getWifiApState( this ) == 13) {
            tv_ip.setText( "本机IP:192.168.43.1" );
        } else {
            tv_ip.setText( "本机IP:" + getLocalIpAddress() );
        }

        checkPermission();
        scan();
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            if (ActivityCompat.checkSelfPermission( this,
                    Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission( this,
                    Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
                String[] strings =
                        {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
                ActivityCompat.requestPermissions( this, strings, 1 );
            }
        } else {
            if (ActivityCompat.checkSelfPermission( this,
                    Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission( this,
                    Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission( this,
                    "android.permission.ACCESS_BACKGROUND_LOCATION" ) != PackageManager.PERMISSION_GRANTED) {
                String[] strings = {android.Manifest.permission.ACCESS_FINE_LOCATION,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        "android.permission.ACCESS_BACKGROUND_LOCATION"};
                ActivityCompat.requestPermissions( this, strings, 2 );
            }
        }

    }


    public int getWifiApState(Context mContext) {
        @SuppressLint("WifiManagerPotentialLeak") WifiManager wifiManager = (WifiManager) mContext.getSystemService( Context.WIFI_SERVICE );
        try {
            assert wifiManager != null;
            Method method = wifiManager.getClass().getMethod( "getWifiApState" );
            return (int) (Integer) method.invoke( wifiManager );
        } catch (Exception e) {
            return -1;
        }
    }

    public String getLocalIpAddress() {
        try {
            String ipv4;
            ArrayList<NetworkInterface> nilist = Collections.list( NetworkInterface.getNetworkInterfaces() );
            for (NetworkInterface ni : nilist) {
                ArrayList<InetAddress> ialist = Collections.list( ni.getInetAddresses() );
                for (InetAddress address : ialist) {
                    if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                        ipv4 = address.getHostAddress();
                        return ipv4;
                    }
                }
            }

        } catch (SocketException ex) {
            Log.e( "localip", ex.toString() );
        }
        return null;
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().removeAllStickyEvents();
        EventBus.getDefault().unregister( this );
        super.onDestroy();
    }


    // 菜单选项事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case Menu.FIRST + 1:
                finish();
                break;
            case Menu.FIRST + 2:
                //
                break;
        }
        return true;
    }

    // 按钮事件
    class ClickEvent implements View.OnClickListener {
        @Override
        public void onClick(View v) {

            if (v == btnDis) {
                // 搜索设备
                LogUtil.e( "hhhh" );
                btnDis.setText( "正在搜索设备..." );
                scan();

            } else if (v == btnAbout) {
                Intent intMain = new Intent( getApplicationContext(), StudentDetailActivity.class );
                Bundle bd = new Bundle();
                bd.putLong( "studentId", studentId );
                bd.putLong( "classId", classId );
                intMain.putExtras( bd );
                startActivity( intMain );
            }
        }

    }


    /**
     * 蓝牙连接
     *
     * @time 2020/12/11 9:46
     */
    private void scan() {
        if (!(BleManager.getInstance().isBlueEnable())) {
            Toast.makeText( mContext, "请先开启蓝牙", Toast.LENGTH_SHORT ).show();
            return;
        }
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setAutoConnect( true )      // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut( 10000 )              // 扫描超时时间，可选，默认10秒
                .build();

        BleManager.getInstance().initScanRule( new BleScanRuleConfig() );


        BleManager.getInstance().scan( new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                lstDevices.clear();
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                if (TextUtils.isEmpty( bleDevice.getName() )) {
                    return;
                }
                lstDevices.add( bleDevice );
                adtDevices.notifyDataSetChanged();
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                btnDis.setText( "重新搜索" );
                for (BleDevice name : scanResultList) {
                    LogUtil.e( "蓝牙名称---", name.getName() );
                }
            }
        } );
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            finish();
//            return true;
//        } else {
//            return super.onKeyDown(keyCode, event);
//        }
//    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(BlueTooth event) {
        if (event.type == 200) {
            //蓝牙配对成功
            dismissProgressDialog();
            startActivity( new Intent( this, TypeActivity.class ) );
            finish();
        } else if (event.type == 500) {
            dismissProgressDialog();
        }
//        if (event.type == 10000) {
//            //连接成功
//            //startActivity( new Intent( this, TypeActivity.class ) );
//            //Toast.makeText( activity, "diopter验光仪蓝牙数据" + event.output, Toast.LENGTH_SHORT ).show();
//            tv_blue.setText( event.output );
//        }
    }

    public void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = this.getWindow();
            //取消状态栏透明
            window.clearFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS );
            //添加Flag把状态栏设为可绘制模式
            window.addFlags( WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS );
            //设置状态栏颜色
            window.setStatusBarColor( Color.parseColor( "#ffffff" ) );
            //设置系统状态栏处于可见状态
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR );
            }

//            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            //让view不根据系统窗口来调整自己的布局
            ViewGroup mContentView = (ViewGroup) window.findViewById( Window.ID_ANDROID_CONTENT );
            View mChildView = mContentView.getChildAt( 0 );
            if (mChildView != null) {
                ViewCompat.setFitsSystemWindows( mChildView, false );
                ViewCompat.requestApplyInsets( mChildView );
            }
        }
        // 这个函数用来设置 Dialog 周围的颜色。系统默认的是半透明的灰色。值设为0则为完全透明。
        this.getWindow().setDimAmount( 3 );
        progressDialog = new ProgressDialog( this );
        //设置进度条风格，风格为圆形，旋转的
        progressDialog.setProgressStyle(
                ProgressDialog.STYLE_SPINNER );
        //设置ProgressDialog 标题
//        progressDialog.setTitle("下载");
        //设置ProgressDialog 提示信息
        progressDialog.setMessage( "请稍后..." );
        //设置ProgressDialog 标题图标
//        progressDialog.setIcon(android.R.drawable.btn_star);
        //设置ProgressDialog 的进度条是否不明确
        progressDialog.setIndeterminate( false );
        //设置ProgressDialog 是否可以按退回按键取消
        progressDialog.setCancelable( true );
        progressDialog.setProgressStyle( R.style.loading_dialog );

    }

    /**
     * 展示加载框
     *
     * @time 2020/4/21 11:16
     */
    public void showProgressDialog() {
        if (NetworkUtil.isNetworkAvailable( this )) {

            // 让ProgressDialog显示
            progressDialog.show();
        }

    }

    public void dismissProgressDialog() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
//            mHandler.postDelayed( sRunnable, 500 );
        }

    }

    private static class MyHandler extends Handler {
        private final WeakReference<MyBlueTooth> mActivity;

        MyHandler(MyBlueTooth activity) {
            mActivity = new WeakReference<MyBlueTooth>( activity );
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            MyBlueTooth activity = mActivity.get();

        }
    }


    private final MyHandler mHandler = new MyHandler( this );

    /**
     * Instances of anonymous classes do not hold an implicit
     * reference to their outer class when they are "static".
     */
    private static final Runnable sRunnable = new Runnable() {
        @Override
        public void run() {
            progressDialog.dismiss();
        }
    };

    /**
     * 展示加载框
     *
     * @time 2020/4/21 11:16
     */
    public void showProgressDialog(Activity mActivity) {
        if (NetworkUtil.isNetworkAvailable( this )) {
            if (mActivity != null) {
                // 这个函数用来设置 Dialog 周围的颜色。系统默认的是半透明的灰色。值设为0则为完全透明。
                this.getWindow().setDimAmount( 3 );
                mProgressDialog = new ProgressDialog( mContext );
                //设置进度条风格，风格为圆形，旋转的
                mProgressDialog.setProgressStyle(
                        ProgressDialog.STYLE_SPINNER );
                //设置ProgressDialog 标题
//        progressDialog.setTitle("下载");
                //设置ProgressDialog 提示信息
                mProgressDialog.setMessage( "连接中..." );
                //设置ProgressDialog 标题图标
//        progressDialog.setIcon(android.R.drawable.btn_star);
                //设置ProgressDialog 的进度条是否不明确
                mProgressDialog.setIndeterminate( false );
                //设置ProgressDialog 是否可以按退回按键取消
                mProgressDialog.setCancelable( true );
                mProgressDialog.setProgressStyle( R.style.loading_dialog );
                // 让ProgressDialog显示
                mProgressDialog.show();
            }

        }

    }

    public void dismissDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }


}